#include "ksyscall.h"
#include "panic.h"
#include "kstdio.h"
#include "dbgio.h"
#include "process.h"
#include "ifs.h"
#include "dri.h"
#include "peloader.h"
//#include "dbgio.h"
void ksyscall_dispatch(syscall_parameter_block * scb){
	//dprintf("Syscall MAGIC:0x%x ID:0x%x PARAM0:0x%x PARAM1:0x%x\n",scb->scp_magic,scb->function_id,scb->parameters[0],scb->parameters[1]);
	if (scb->scp_magic != 0xBADCA11)
		panic("CORRUPT_SYSCALL","Magic number invalid",0);
	switch (scb->function_id){
		case SC_READ:
			scb->result = read((KFILE) scb->parameters[0],(uint8_t *)scb->parameters[1],scb->parameters[2]);
			break;
		case SC_WRITE:
			scb->result = write((KFILE) scb->parameters[0],(uint8_t *)scb->parameters[1],scb->parameters[2]);
			//dprintf("Write result:%i errno:0x%x",scb->result,scb->errno);
			break;
		case SC_SEEK:
			scb->result = seek((KFILE) scb->parameters[0],scb->parameters[1],(uint8_t)scb->parameters[2]);
			break;
		case SC_AVAIL:
			scb->result = (uint32_t) pipe_available((KFILE) scb->parameters[0]);
			break;
		case SC_OPEN:
			scb->result = open((char *)scb->parameters[0],scb->parameters[1],scb->parameters[2]);
			break;
		case SC_CLOSE:
			scb->result = close ((KFILE) scb->parameters[0]);
			break;
		case SC_MKLOOP:
			scb->result = create_loop((int)scb->parameters[0]);
			break;
		case SC_REGDR:
			dri_register_driver((dri_driver_descriptor_t *)scb->parameters[0]);
			break;
		case SC_REGSF:
			dri_register_specfile(
				(char *)scb->parameters[0],
				scb->parameters[1],
				scb->parameters[2],
				scb->parameters[3],
				(read_fs_t)scb->parameters[4],
				(write_fs_t)scb->parameters[5]);
			break;
		case SC_REGIR:
			dri_register_interrupt((uint8_t)scb->parameters[0],(dri_interrupt_handler)scb->parameters[1]);
			break;
		case SC_GETPID:
			scb->result = get_current_process()->pid;
			break;
		case SC_EXIT:
			exit(scb->parameters[0]);
			break;
		case SC_CHDIR:
			scb->result = chdir((char *)scb->parameters[0]);
			break;
		case SC_MKDIR:
			scb->result = mkdir((char *)scb->parameters[0]);
			break;
		case SC_MOUNT:
			scb->result = kmount((char *)scb->parameters[0],(char *)scb->parameters[1],(char *)scb->parameters[2]);
			break;
		case SC_UMOUNT:
			scb->result = kumount((char *)scb->parameters[0],(char *)scb->parameters[1]);
			break;
		case SC_EXECVE:
			scb->result = exec_pe((char *)scb->parameters[0]);
			break;
		case SC_SBRK:
			//dprintf("MORECORE:0x%x",scb->parameters[0]);
			break;

		default:
			dprintf("FID:0x%x",scb->function_id);
			panic("CORRUPT_SYSCALL","Unknown function",0);
	}
	scb->errno = get_current_process()->errno;
	//dprintf("Result: 0x%x. Errno:0x%x\n",scb->result,scb->errno);
}